<?php

class JqGridActiveJsonProvider extends CActiveDataProvider {

    public $columnsModel;

    public function __construct($modelClass, $config=array()) {
        parent::__construct($modelClass, $config);

        $pagination = $this->getPagination();
        if (isset($_GET['page'])
            )$pagination->setCurrentPage($_GET['page'] - 1);
        if (isset($_GET['rows'])
            )$pagination->setPageSize($_GET['rows']);

        $criteria = $this->getCriteria();
        $criteria->order = ($_GET['sidx'] ? $_GET['sidx'] : 1) . ' ' . $_GET['sord'];

        $this->columnsModel->init();
        $criteria->select = implode(",", $this->columnsModel->colNames);

        // search filter
        if ($_GET['_search']) {
            foreach($this->columnsModel->colNames as $column){
                if(isset($_GET[$column]))
                    $criteria->compare($column, $_GET[$column]);
            }

        }
    }

    public function getJsonData() {

        foreach ($this->getData() as $i => $row) {
            $responce->rows[$i]['id'] = $row->getPrimaryKey();
            $responce->rows[$i]['cell'] = array_values($row->getAttributes());
        }

        $responce->records = $this->getTotalItemCount();
        $responce->total = ceil($responce->records / $_GET['rows']);
        $responce->page = $_GET['page'];

        return CJSON::encode($responce);
    }

}
